package com.yzl.springboot.springboot.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.yzl.springboot.springboot.domain.User;
import com.yzl.springboot.springboot.service.impl.UserServiceImpl;
import com.yzl.springboot.springboot.utils.JsonData;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;


/**
 * @Title: LoginFilter
 * @Author: 姚志立
 * @Description:
 * @Date: 2020/5/25 10:31
 * @Version: 1.0
 */
@WebFilter(urlPatterns = "/api/v1/pri/*", filterName = "loginFilter")
public class LoginFilter implements Filter {
    private static final ObjectMapper objectMapper=new ObjectMapper();

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("init===========");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        System.out.println("do===========");
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        String token = req.getHeader("token");
        if (StringUtils.isEmpty(token)) {
            token = req.getParameter("token");
        }
        if (!StringUtils.isEmpty(token)) {
            //判断token是否合法
            User user = UserServiceImpl.sessionMap.get(token);
            if (user != null) {
                chain.doFilter(request, response);
            }else {
                JsonData jsonData=JsonData.buildError(-2, "登陆失败，token无效");
                String jsonStr = objectMapper.writeValueAsString(jsonData);
                renderJson(resp, jsonStr);
            }
        }else {
            JsonData jsonData=JsonData.buildError(-3, "未登录");
            String jsonStr = objectMapper.writeValueAsString(jsonData);
            renderJson(resp, jsonStr);
        }
    }

    private void renderJson(HttpServletResponse response, String json) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        try (PrintWriter writer = response.getWriter()) {
            writer.print(json);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void destroy() {
        System.out.println("destroy=========");
    }
}
